$.fn.selection = function () {
    var s, e, range, stored_range;
    if (this[0].selectionStart == undefined) {
        var selection = document.selection;
        if (this[0].tagName.toLowerCase() != "textarea") {
            var val = this.val();
            range = selection.createRange().duplicate();
            range.moveEnd("character", val.length);
            s = (range.text == "" ? val.length : val.lastIndexOf(range.text));
            range = selection.createRange().duplicate();
            range.moveStart("character", -val.length);
            e = range.text.length;
        } else {
            range = selection.createRange(),
                stored_range = range.duplicate();
            stored_range.moveToElementText(this[0]);
            stored_range.setEndPoint('EndToEnd', range);
            s = stored_range.text.length - range.text.length;
            e = s + range.text.length;
        }
    } else {
        s = this[0].selectionStart,
            e = this[0].selectionEnd;
    }
    var te = this[0].value.substring(s, e);
    return {start: s, end: e, text: te};
};



function HTMLDecode(text)
{
    var temp = document.createElement("div");
    temp.innerHTML = text;
    var output = temp.innerText || temp.textContent;
    temp = null;
    output=output.replace(/\"/gi,"\"");
    return output;
}



$(document).ready(function () {
    $("#url").bind('keydown', function (event) {
        if (event.keyCode == "13") {
            $('#B1').click();
        }
    });

    document.onmousemove=function(e){
        var div=document.getElementById("shuxian");
        div.style.left=e.clientX-$('#css2').offset().left+10+"px";
        div.style.top=e.clientY-$('#css2').offset().top+"px";
    }
});

function meihua(){
    $.ajax({
        type:'POST',
        async:true,//true是异步，false是同步
        timeout : 20000,//20秒
        url: "curl.php?url="+$('#url').val()+"&s="+Math.random(), //"?s="+Math.random(),  //网址请以/开头否则可能不带cookies过去
        data: {'code':$('#css').val(),'operate':'beauty'}, //data里面的值不要有未定认或null值 "{'name1':'value', 'name2':'value'}"
        dataType: "json",//html,text,json,jsonp,excel,script
        success: function(data){
            $('#css').val(data.text);
        }
    });
    $.ajax({
        type:'POST',
        async:true,//true是异步，false是同步
        timeout : 20000,//20秒
        url: "curl.php?url="+$('#url').val()+"&s="+Math.random(), //"?s="+Math.random(),  //网址请以/开头否则可能不带cookies过去
        data: {'code':$('#css2').val(),'operate':'beauty'}, //data里面的值不要有未定认或null值 "{'name1':'value', 'name2':'value'}"
        dataType: "json",//html,text,json,jsonp,excel,script
        success: function(data){
            $('#css2').val(data.text);
        }
    });
}

$(document).ready(function(){
//       $.delegate($("#source"),"blur,change", function(){
//            $("#ifrcv")[0].contentWindow.document.documentElement.innerHTML=$("#source").val();
//        }());

    $(window.frames["ifrcv"].document).delegate("div","mouseover",function(){
        $(this).addClass("selected");
    });

    $(window.frames["ifrcv"].document).delegate("div","mouseout",function(){
        $(this).removeClass("selected");
    });

})

function getSel() {
    var oRange;
    var intCount = 0;
    var intTotalCount = 0;
    var wz=$("#source").val().indexOf("id=\"main\"");
//        document.designMode = 'on';
//        myform.source.focus();
    myform.source.setSelectionRange(wz, wz+9);
//        var isIE = !(!document.all);
//        myform.source.focus();
    myform.source.selectionStart=wz;
    myform.source.selectionEnd=wz+9;
//        myform.source.selectionStart = myform.source.selectionEnd = wz;

}

function selecttext(idname){
    var t = document.getElementById(idname);
    if (window.getSelection) {
        if (t.selectionStart != undefined && t.selectionEnd != undefined) {
            return t.value.substring(t.selectionStart, t.selectionEnd);
        } else {
            return "";
        }
    } else {
        return document.selection.createRange().text;
    }
}


function textboxSelect(oTextbox, iStart, iEnd) {
    var isIE = !(!document.all);
    switch(arguments.length) {
        case 1:
            oTextbox.select();
            break;
        case 2:
            iEnd = oTextbox.value.length;
        case 3:
            if (oTextbox.createTextRange) {
                var oRange = oTextbox.createTextRange();
                oRange.moveStart("character", iStart);
                oRange.moveEnd("character", -oTextbox.value.length + iEnd);
                oRange.select();
            } else if (oTextbox.createTextRange){
                oTextbox.focus();
                var oRange =oTextbox.setSelectionRange(iStart, iEnd);

            }
    }
    oTextbox.focus();
}

function geturl(){
    $.ajax({
        type:'POST',
        async:true,//true是异步，false是同步
        timeout : 20000,//20秒
        url: "/getjs/index.php?url="+encodeURIComponent($('#url').val())+"&B1=1&s="+Math.random(), //"?s="+Math.random(),  //网址请以/开头否则可能不带cookies过去
        data: {'code':$('#source').val(),'operate':'beauty'}, //data里面的值不要有未定认或null值 "{'name1':'value', 'name2':'value'}"
        dataType: "html",//html,text,json,jsonp,excel,script
        success: function(str){
            $('#source').val(str);
            sx2();
        }
    });
}

function sxSource(){
    var txt = $("#source").val();
    fx(txt,function(){
        $("body", window.frames["ifr"].document).html($("#css").val());
        meihua();
    });
}

function sx() {
    var txt = $("#css").val();
    fx(txt,function(){
        $("body", window.frames["ifr"].document).html(txt);
        meihua();
    });
}

function sx2(){
    $("#ifrcv")[0].contentWindow.document.documentElement.innerHTML=$("#source").val();

    $(window.frames["ifrcv"].document).delegate("div","mouseover",function(event){
        event.stopPropagation();
        $(this).addClass("selected").css({"background-color":"#eee"}).attr("id","main");
    });

    $(window.frames["ifrcv"].document).delegate("div","mouseout",function(){
        $(this).removeClass("selected").css({"background-color":""}).removeAttr("id");
    });

    $(window.frames["ifrcv"].document).delegate("div","click",function(event){
        event.stopPropagation();
        $("#source").val($("#ifrcv")[0].contentWindow.document.documentElement.innerHTML);
        getSel();
        tqcss();
    });

}

function tqcss() {
    var main=$("#main").val();
    var re=new RegExp(main,"gi");
    if (!re.test($("#source").val())) {
        layer.alert('请先在源代码框的html标签里用  id="'+main+'" 标注需要抓取的代码块');
        return;
    }
    var index = layer.load(1, {
        shade: [0.1, 'yellow'] //0.1透明度的白色背景
    });
    var nr=encodeURIComponent($("#source").selection().text);
    if(nr==""){
        nr="id=\"main\"";
    }
    $.ajax({
        type: 'POST',
        async: true,//true是异步，false是同步
        timeout: 40000,//40秒
        url: "?act=fx&XDEBUG_SESSION_START=34334&main="+main+"&r=" + Math.random(),
        data: {
            "source": encodeURIComponent($("#source").val()),
            "nr":nr,
        }, //data里面的值不要有未定认或null值
        dataType: "json",//html,text,json,excel,script
        success: function (data) {
            //debugger;
            layer.close(index);
            $("#css").val(data.body);
            $("#css2").val(data.body);
            $("body", window.frames["ifr"].document).html(data.body);
            meihua();
            layer.msg('分析完成！您还可以在结果框里修改，可以所见所得哦~~');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layer.close(index);
            layer.msg('在分析过程中出错了！');
        },
        complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数
            if (status == 'timeout') {//超时,status还有success,error等值的情况
                layer.msg('文件太复杂，分析超时了!');
            }
        }
//,cache:false, // disable cache(禁用IE缓存)
//,ifModified:true
    });

}



function fx(txt,fun){
    $.ajax({
        type:'POST',
        async:true,//true是异步，false是同步
        timeout : 20000,//20秒
        url: "/getjs/index.php?XDEBUG_SESSION_START=334&act=fx&s="+Math.random(), //"?s="+Math.random(),  //网址请以/开头否则可能不带cookies过去
        data: {'source':txt,'nr':encodeURIComponent('id="main"')}, //data里面的值不要有未定认或null值 "{'name1':'value', 'name2':'value'}"
        dataType: "json",//html,text,json,jsonp,excel,script
        success: function(data){
            $('#css').val(data.body);
            $('#css2').val(data.body);
            fun();
        }
    });
}

function leftxz(){
    $("#css2").focus();
    var source=selecttext("css2").replace(/<style>[\S\s]*<\/style>/gi,"");
    var txt = $("#css2").val().replace(/<\/style>[\S\s]*$/gi,"</style>")+"\r\n"+source;//
     fx(txt,function(){
        $("body", window.frames["ifr"].document).html(txt);
        meihua();
    });

}